package com.gcit.seniorWish.web.modular.system.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.gcit.seniorWish.core.base.controller.BaseController;
import com.gcit.seniorWish.core.base.tips.Tip;
import com.gcit.seniorWish.core.exception.GunsException;
import com.gcit.seniorWish.core.node.ZTreeNode;
import com.gcit.seniorWish.core.support.BeanKit;
import com.gcit.seniorWish.core.util.ToolUtil;
import com.gcit.seniorWish.web.common.constant.dictmap.MenuDict;
import com.gcit.seniorWish.web.common.constant.enums.MenuStatusEnum;
import com.gcit.seniorWish.web.common.constant.factory.ConstantFactory;
import com.gcit.seniorWish.web.common.persistence.model.Menu;
import com.gcit.seniorWish.web.core.annotion.BussinessLog;
import com.gcit.seniorWish.web.core.annotion.Permission;
import com.gcit.seniorWish.web.core.exception.BizExceptionEnum;
import com.gcit.seniorWish.web.core.log.LogObjectHolder;
import com.gcit.seniorWish.web.modular.system.dao.MenuDao;
import com.gcit.seniorWish.web.modular.system.service.IMenuService;
import com.gcit.seniorWish.web.modular.system.warpper.MenuWarpper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 菜单控制器
 *
 * @author fengshuonan
 * @Date 2017年2月12日21:59:14
 */
@Controller
@RequestMapping("/menu")
public class MenuController extends BaseController {

    private static String PREFIX = "/system/menu";


    @Resource
    private MenuDao menuDao;

    @Autowired
    private IMenuService menuService;

    /**
     * 跳转到菜单列表列表页面
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "/menu.html";
    }

    /**
     * 跳转到菜单列表列表页面
     */
    @RequestMapping(value = "/menuAdd")
    public String menuAdd() {
        return PREFIX + "/menuAdd.html";
    }

    /**
     * 跳转到菜单详情列表页面
     */
    @RequestMapping(value = "/menuEdit/{menuId}")
    public String menuEdit(@PathVariable String menuId, Model model) {
        if (ToolUtil.isEmpty(menuId)) {
            throw new GunsException(BizExceptionEnum.REQUEST_NULL);
        }
        Menu menu = this.menuService.selectById(menuId);
        model.addAttribute("menu", menu);
        LogObjectHolder.me().set(menu);
        return PREFIX + "/menuInfo.html";
    }

    /**
     * 修改菜单
     */
    @Permission
    @RequestMapping(value = "/edit")
    @BussinessLog(value = "修改菜单", key = "name", dict = MenuDict.class)
    @ResponseBody
    public Tip edit(Menu menu, BindingResult result) {
        if (result.hasErrors()) {
            throw new GunsException(BizExceptionEnum.REQUEST_NULL);
        }
        //设置父级菜单编号
        menuSetPid(menu);
        this.menuService.updateById(menu);
        return SUCCESS_TIP;
    }

    /**
     * 获取菜单列表
     */
    @Permission
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(@RequestParam(required = false) String menuName, @RequestParam(required = false) Integer rank) {
        EntityWrapper<Menu> ew = new EntityWrapper<>();
        if (StrUtil.isNotBlank(menuName)) {
            ew.like("name", menuName);
        }
        if (rank != null) {
            ew.eq("rank", rank);
        }
        ew.orderBy("num");
        List<Map<String, Object>> menus = menuService.selectMaps(ew);
        return super.warpObject(new MenuWarpper(menus));
    }

    /**
     * 新增菜单
     */
    @Permission
    @RequestMapping(value = "/add")
    @BussinessLog(value = "菜单新增", key = "name", dict = MenuDict.class)
    @ResponseBody
    public Tip add(@Valid Menu menu, BindingResult result) {
        if (result.hasErrors()) {
            throw new GunsException(BizExceptionEnum.REQUEST_NULL);
        }
        //设置父级菜单编号
        menuSetPid(menu);
        menu.setStatus(MenuStatusEnum.ENABLE.getCode());
        this.menuService.insert(menu);
        return SUCCESS_TIP;
    }

	/**
	 * 删除菜单
	 */
	@Permission
	@RequestMapping(value = "/remove")
	@BussinessLog(value = "删除菜单", key = "menuId", dict = MenuDict.class)
	@ResponseBody
	public Tip remove(@RequestParam String menuId) {
		if (ToolUtil.isEmpty(menuId)) {
			throw new GunsException(BizExceptionEnum.REQUEST_NULL);
		}

		// 缓存菜单的名称
		LogObjectHolder.me().set(ConstantFactory.me().getMenuName(menuId));

		this.menuService.delMenuContainSubMenus(menuId);
		return SUCCESS_TIP;
	}

	/**
	 * 更新菜单状态
	 */
	@Permission
	@RequestMapping(value = "/updateStatus")
	@BussinessLog(value = "更新菜单状态", key = "menuId", dict = MenuDict.class)
	@ResponseBody
	public Tip updateStatus(Menu menu) {
		if (menu == null || StrUtil.isBlank(menu.getId())) {
			throw new GunsException(BizExceptionEnum.REQUEST_NULL);
		}
		this.menuService.updateById(menu);
		return SUCCESS_TIP;
	}


    /**
     * 获取菜单列表
     */
    @RequestMapping(value = "/menuTreeList")
    @ResponseBody
    public List<ZTreeNode> menuTreeList(String initId) {
        return this.menuDao.menuTreeList();
    }

    /**
     * 获取菜单列表(选择父级菜单用)
     */
    @RequestMapping(value = "/selectMenuTreeList")
    @ResponseBody
    public List<ZTreeNode> selectMenuTreeList() {
        List<ZTreeNode> roleTreeList = this.menuDao.menuTreeList();
        roleTreeList.add(ZTreeNode.createParent());
        return roleTreeList;
    }

    /**
     * 根据角色id查询菜单
     */
    @RequestMapping(value = "/menuTreeListByRoleId/{roleId}")
    @ResponseBody
    public List<ZTreeNode> menuTreeListByRoleId(@PathVariable String roleId) {
        List<String> menuIds = this.menuDao.getMenuIdsByRoleId(roleId);
        if (ToolUtil.isEmpty(menuIds)) {
            return this.menuDao.menuTreeList();
        } else {
            return this.menuDao.menuTreeListByMenuIds(menuIds);
        }
    }


    /**
     * 根据请求的父级菜单id
     */
    private void menuSetPid(Menu menu) {
        if (ToolUtil.isEmpty(menu.getPid()) || menu.getPid().equals("0")) {
            menu.setRank(1);
            menu.setPids("[0]");
        } else {
            Menu pMenu = menuService.selectById(menu.getPid());
            Integer rank = pMenu.getRank();
            menu.setRank(rank + 1);
            menu.setPids(pMenu.getPids() + "[" + pMenu.getPid() + "],");
        }
    }

}
